#include "file_saver.h"

file_saver::file_saver()
{
    this->buffer=0;
    this->indicator=0;
}

void file_saver::open(QString path)
{
    this->file.open (path.toStdString().c_str(), std::ios_base::out|std::ios_base::binary );
    if(!file.is_open())
    {
        qDebug()<<"nie udalo sie otworzyc pliku";
    }
}

void file_saver::save(int value, int length)
{
    //qDebug() << "save" << value << length;
    if(file.is_open())
    {
         buffer=buffer<<length;
        buffer= buffer | (value & (((long long)1<<length)-1));
        this->indicator+=length;
        while(indicator>=8)
        {
                byte=((buffer& (0xFF << (indicator-8))))>>(indicator-8);
                file.put(byte);
                //qDebug() << "bufor" << byte;
                indicator-=8;
                buffer=buffer& ((1<<indicator)-1);
        }
    }
    else
    {
        qDebug()<<"Open file first";
    }
}

void file_saver::close(void)
{
    byte=(buffer<<(8-indicator))&0xFF;
    file.put(byte);
    byte=(8-indicator)&0xFF;
    file.put(byte);
    file.close();
}
